
<@c.html>
<div class="col-sm-6">
    <div class="panel panel-_default">
        <div class="panel-heading">
            <h1 class="panel-title" style="font-size: 28px;">
                <i class="fa fa-database" style="font-size: 28px;"></i>
                角色
            </h1>
        </div>
        <div class="panel-body">
            <div class="row">
                <table id="table"></table>
                <div id="toolbar">
                    <a href="./addView" class="btn btn-success">新增</a>
                    <button class="btn btn-success" id="delete">删除</button>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="col-sm-6">
    <div class="panel panel-_default">
        <div class="panel-heading">
            <h1 class="panel-title" style="font-size: 28px;">
                <i class="fa fa-database" style="font-size: 28px;"></i>
                菜单
            </h1>
        </div>
        <div class="panel-body">
            <button class="btn btn-success" id="btn-save">保存</button>
            <div id="menu">

            </div>
        </div>
    </div>
</div>
</@c.html>
<script type="application/javascript">
    $(function(){
        $('#table').bootstrapTable({
            url: '.',
            columns: [{
                field: 'ck',
                checkbox: true
            },{
                field: 'id',
                title: 'id',
                visible : false
            },{
                field: 'name',
                title: '名称'
            },{
                field: 'code',
                title: '编码'
            }],
            pagination: true,
            sidePagination: 'server',
            paginationLoop: false,
            toolbar: "#toolbar",
            showToggle : true,
            striped: true,
            cache : false,
            idField: "id",
            showRefresh : true,
            clickToSelect : true,
            onDblClickRow: update,
            onClickRow: loadMenu
        });

        $("#search").click(function(){
            var params = {};
            $.each($("#query-form").serializeArray(), function(i, data) {
                var creation = $("#query-form").find('*[name="' + data.name + '"]').attr("creation");
                params[data.name] =  creation + "," + data.value;
            });
            $('#table').bootstrapTable('refresh', {query : params});
        });

        $('#delete').click(function(){
            var selections = $('#table').bootstrapTable("getSelections");
            if(selections.length == 0) return;

            var ids = [];
            $.each(selections, function(i, selection){ids.push(selection.id)});

            $.ajax({
                type : "delete",
                url : '.?ids=' + ids.join(","),
                contentType:"json",
                success:function (result) {
                    console.log(result);
                    $('#table').bootstrapTable('refresh');
                },
                error:function(xmlHttpRequest , message,  error){
                    console.log(message);
                }
            });
        })

        function update(row, $element, field){
            window.location.href = "./updateView?id=" + row.id;
        }

        function loadMenu(row, $element){
            $.get("../sysRoleMenu",{role_id: "eq," + row.id}, function(data){
                $.each(data, function(i, roleMenu){
                    var searchNodes = $treeview.treeview("findNodes", [roleMenu.menuId, 'g', 'id']);
                    if(searchNodes.length == 0)
                        return;
                    if(searchNodes[0].level == 1){
                        return;
                    }
                    var id = searchNodes[0].id;
                    var nodes = $treeview.treeview("getNodes");

                    for(var j = 0; j < nodes.length; j++){
                        if(nodes[j].id == id){
                            $treeview.treeview("checkNode", j);
                            return;
                        }
                    }
                });
            });
        }

        var $treeview = {};

        $.get("../sysMenu/", function (data) {
            console.log(data);

            var defaultData = [];
            $.each(data, function(i, menu){
                if(menu.level === 1){
                    menu.text = menu.name;
                    defaultData.push(menu);
                }
            });


            $.each(data, function(i, subMenu){
               $.each(defaultData, function(j, menu){
                   if(subMenu.parentId == menu.id){
                       if(!menu.nodes)menu.nodes = [];
                       subMenu.text = subMenu.name;
                       menu.nodes.push(subMenu);
                   }
               })
            });

            $treeview = $('#menu').treeview({
                data: defaultData,
                showIcon: false,
                showCheckbox: true,
                highlightSelected : false,
                onNodeChecked: function(event, node, options) {
                    console.log(node.text, options.ignoreChildren);

                    // 父级节点被选中，那么子节点都要选中
                    if(node.nodes != null && !!!options.ignoreChildren) {
                        $.each(node.nodes, function(index, value) {
                            $treeview.treeview('checkNode', value.nodeId);
                        });
                    }

                    // 子节点选中的时候，要根据情况判断父节点是否要全部选中

                    // 父节点
                    var parentNode = $treeview.treeview('getParent', node.nodeId);

                    if(parentNode["nodeId"] == null) return;


                    var isAllchecked = true; // 是否全部选中

                    // 当前子节点的所有兄弟节点，也就是获取省下面的所有市
                    var siblings = $treeview.treeview('getSiblings', node.nodeId);
                    for(var i in siblings) {
                        // 有一个没选中，则不是全选
                        if(!siblings[i].state.checked) {
                            isAllchecked = false;
                            break;
                        }
                    }

                    // 全选，则打钩
                    if(isAllchecked) {
                        $treeview.treeview('checkNode', [parentNode.nodeId, {
                            ignoreChildren : true
                        }]);
                    }

                },
                onNodeUnchecked: function(event, node, options) {
                    console.log("取消选中项目为：" + node);

                    // 选中的是父级节点
                    if(node.nodes != null && !!!options.ignoreChildren) {
                        // 这里需要控制，判断是否是因为子节点引起的父节点被取消选中
                        // 如果是，则只管取消父节点就行了
                        // 如果不是，则子节点需要被取消选中
                        $.each(node.nodes, function(index, value) {
                            $treeview.treeview('uncheckNode', value.nodeId);
                        });
                    }

                    // 子节点被取消选中
                    var parentNode = $treeview.treeview('getParent', node.nodeId);

                    if(parentNode["nodeId"] != null) {
                        $treeview.treeview('uncheckNode', [parentNode.nodeId, {
                            ignoreChildren : true
                        }]);
                    };
                }
            });

            $("#btn-save").click(function(){
                var selections = $('#table').bootstrapTable("getSelections");
                if(selections.length != 1) {
                    bootbox.alert("只能选择一条记录!");
                    return;
                }
                var roleId = selections[0].id;

                var checkList = $treeview.treeview("getChecked");

                console.log(checkList);

                var params = [];
                $.each(checkList, function(i, menu){
                   params.push({
                       roleId: roleId,
                       menuId: menu.id
                   }) ;
                });

                $.ajax({
                    type : "post",
                    url : '../sysRoleMenu/',
                    contentType:"json",
                    headers: {"Content-Type":"application/json"},
                    data: JSON.stringify(params),
                    success:function (result) {
                        console.log(result);
                        bootbox.alert("保存成功");
                    },
                    error:function(xmlHttpRequest , message,  error){
                        bootbox.alert("error");
                        console.log(message);
                    }
                });
            });
        });
    });

</script>